// utils/loginUtils.js
// 基础配置

import getBaseUrl from './baseUrl'
import { http } from './requestUtil';
// const baseConfig = 'https://xit-edu.cn/2502boleapi/bole';
const baseConfig =getBaseUrl+'/bole'
export const login = (username, password, callback) => {
    uni.showLoading({ title: '登录中...', mask: true });
    uni.request({
        url: `${baseConfig}/login`, // 若依的登录接口地址
        data: {
            username: username,
            password: password
        },
        method: 'POST',
        header: { 'content-type': 'application/json' },
        success: (res) => {
			
            const { token:token, code: responseCode,user:userInfo } = res.data;
            if (responseCode === 200) {
				saveToken(token,userInfo)
                
			 uni.switchTab({
			            url: '/pages/home/home' // 确保这个路径是正确的 tabBar 页面路径
			        });
                if (callback) {
                    callback();
                }
            } else {
				console.log(res)
                uni.showToast({ title:res.data.msg, icon: 'error' });
            }
        },
        fail: (res) => {
			console.log(res)
            uni.showToast({ title: '登录服务器失败！', icon: 'error' });
        },
        complete: () => {
            uni.hideLoading();
        }
    });
};
// wxlogin((error, userInfo) => {
//     if (error) {
//         console.error('登录出错:', error);
//     } else {
//         console.log('登录成功，用户信息:', userInfo);
//         // 在这里可以进行后续操作，如更新页面数据等
//     }
// }); 
export const wxlogin = (callback) => {
	wx.showLoading()
	uni.login({
	  success: (res) => {
	    if (res.code) {
	      const { miniProgram } = uni.getAccountInfoSync();
	      uni.request({
	        url: `${baseConfig}/wxlogin`,
	        data: {
	          code: res.code,
	          appId: miniProgram.appId
	        },
	        method: 'POST',
	        header: { 'content-type': 'application/json' },
	        success: (res) => {
		  //直接解构
	          const { data, code: responseCode,wxInfo,authInfo,token:token } = res.data;
	          if (responseCode === 200) {
			// uni.setStorageSync('token', data.token);
	            const { wxInfo = {}, userInfo = {}} = res.data;
				console.log(token)
				console.log(userInfo)
	           saveToken(token,userInfo)
			   uni.switchTab({
			              url: '/pages/home/home' // 确保这个路径是正确的 tabBar 页面路径
			          });
			   
	          } else {
				  console.log(res)
				uni.showToast({ title:"登录失败 请重试", icon: 'error' });
	          }
	        },
	        fail: () => {
	          uni.showToast({ title: '登录服务器失败！', icon: 'error' });
	        },
	        complete: () => {
	          uni.hideLoading();
	        }
	      });
	    } else {
	     uni.showToast({ title:"登录失败1请重试", icon: 'error' });
	      uni.hideLoading();
	    }
	  },
	  fail: () => {
	console.log('登录失败！' + res.errMsg);
	console.error('登录失败！' + res.errMsg);
	    uni.showToast({ title:res, icon: 'error' });
	    uni.hideLoading();
	  }
	});
};
export const updateUserInfo=async ()=>{
	const userInfo =await http.get("/bole/userinfo/"+uni.getStorageSync("userId"))
	uni.setStorageSync('userInfo',userInfo.data)
	console.log(uni.getStorageSync("userInfo"))
}
// 保存 token 的函数示例
const saveToken = (token,userInfo) => {
	console.log(userInfo)
	uni.setStorageSync('userId',userInfo.userId)
	// console.log(uni.getSto)
	uni.setStorageSync('userInfo',userInfo)
    uni.setStorageSync('token', token);
};
const saveInfo = (token,userInfo) => {
	console.log(userInfo)
	uni.setStorageSync('userId',userInfo.userId)
	// console.log(uni.getSto)
	uni.setStorageSync('userInfo',userInfo)
    uni.setStorageSync('token', token);
};
// 获取 token
export const getToken = () => {
  const authInfo = uni.getStorageSync('userInfo');
  const token = uni.getStorageSync('token');
  if (authInfo && token) {
	  // console.log(token)
    return 'Bearer ' + token;
  }
  return null;
};

// 删除用户相关信息
export const removeUserInfo = (callback) => {
  uni.showLoading({ title: '退出中...' });
  uni.removeStorage({
    key: 'wxInfo',
    success: () => {
      uni.removeStorage({
        key: 'authInfo',
        success: (res) => {
          callback && callback(res);
          uni.showToast({ title: '退出成功！', icon: 'success' });
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    }
  });
};
// utils/device.js
export function getSafePlatform() {
  const systemInfo = uni.getSystemInfoSync() || {}
  return (systemInfo.platform || '').toLowerCase()
}